package com.steven.ourcontest.login.api

import com.steven.ourcontest.login.bean.CodeResponse
import com.steven.ourcontest.login.bean.LoginResponse
import com.steven.ourcontest.login.bean.SignUpResponse
import com.steven.ourcontest.net.BaseResponse
import com.steven.ourcontest.net.NetConstants
import io.reactivex.Observable
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit封装
 */
class LoginApi private constructor() {
    private val mRetrofit: Retrofit
    private val mApiService: LoginApiService

    companion object {
        const val DEFAULT_TIMEOUT = 5
        val instance: LoginApi by lazy {
            LoginApi()
        }
    }

    init {
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(
            DEFAULT_TIMEOUT.toLong(),
            TimeUnit.SECONDS
        )
        mRetrofit = Retrofit.Builder()
            .client(builder.build())
            .baseUrl(NetConstants.LOGIN_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        mApiService = mRetrofit.create(LoginApiService::class.java)
    }

    fun sendCode(email:String,code:Int): Observable<BaseResponse<CodeResponse>> {
        return mApiService.sendCode(email,code)
    }

    fun quickLogin(email:String): Observable<BaseResponse<LoginResponse>> {
        return mApiService.quickLogin(email)
    }

    fun login(email:String,password:String): Observable<BaseResponse<LoginResponse>> {
        return mApiService.login(email,password)
    }

    fun signUp(email:String,password:String): Observable<BaseResponse<SignUpResponse>> {
        return mApiService.signUp(email,password)
    }
}